import { cutFile } from "./cutFile.js";

// 设置允许上传最大文件为10G
const fileMaxSize = 1024 * 1024 * 1024 * 10;
// 存储文件集合
let fileList = [];
// 上传队列
let uploadQueue = []

// 选择文件
const selectFile = document.querySelector('input[id="selectFile"]');
selectFile.onchange = async (e) => {
  e.preventDefault()
  changeSelectFiles(e)
}
// 选择文件夹
const selectFileDirectory = document.querySelector('input[id="selectFileDirectory"]');
selectFileDirectory.onchange = async (e) => {
  e.preventDefault()
  changeSelectFiles(e)
}

// 选择文件
const changeSelectFiles = async (e) => {
  const filenameRegex = /([^/\\]+)\.([a-zA-Z0-9]+)$/
  for (const file of e.target.files) {
    if (fileSizeExceeds(file, fileMaxSize)) {
      layer.msg(`文件超过最大允许尺寸：${formatFileSize(fileMaxSize)}`, {
        offset: '6px',
        icon: 5
      });
      console.warn(`文件[${file.name}](${formatFileSize(file.size)})超过最大允许尺寸：${formatFileSize(fileMaxSize)}`);
      continue
    }
    const fileInfo = file.name.match(filenameRegex) || ['', file.name]
    // 分片计算MD5
    const chunks = await cutFile(file);
    const curMd5 = chunks.slice(-1)[0].hash;
    // 判断文件是否已经上传过
    const newValue = fileList.findIndex(item => item.md5 === curMd5);
    if (newValue === -1) {
      // 保存分片内容
      fileList.push({
        id: curMd5,
        md5: curMd5,
        chunks: chunks,
        name: fileInfo[1],
        size: file.size,
        type: fileInfo[2],
        status: 1,
        process: 0,
        uploaded: '',
        fileObj: file,
        path: file.webkitRelativePath
      })
    }
  }
  loadFileTable()
}

// 判断文件大小
function fileSizeExceeds(file, maxSize) {
  return file.size > maxSize
}

// 清空文件列表
const clearFiles = document.querySelector('button[id="clearFiles"]');
clearFiles.onclick = (e) => {
  e.preventDefault()
  if (fileList.length < 0) return
  fileList = []
  loadFileTable()
}

// 上传文件

const uploadFiles = document.querySelector('button[id="uploadFiles"]');
uploadFiles.onclick = (e) => {
  e.preventDefault()
  uploadQueue = [...fileList]
  console.log(uploadQueue);
}

// 渲染表格
function loadFileTable() {
  console.log(fileList);
  layui.use(['table'], function () {
    var $ = layui.jquery,
      table = layui.table;
      $('#fileCount').text(fileList.length);
      let fileSizeCount = 0;
      // 遍历fileList中的对象，统计size和
      fileList.forEach(item => {
        fileSizeCount += item.size;
      })
      $('#fileSizeCount').text(formatFileSize(fileSizeCount));
    table.reload('fileTable', {
      data: fileList
    })
  });
}

// 文件大小格式转换
function formatFileSize(size) {
  let temp = ''
    if (size < 1024) {
      temp = size + 'B'
    } else if (size < 1024 * 1024) {
      temp = (size / 1024).toFixed(2) + 'KB'
    } else if (size < 1024 * 1024 * 1024) {
      temp = (size / (1024 * 1024)).toFixed(2) + 'MB'
    } else {
      temp = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
    }
    return temp
}

// 初始化表格，文件集合渲染列表展示
initFileTable()
function initFileTable() {
  layui.use(['element', 'table'], function () {
    var $ = layui.jquery
      , element = layui.element,
      table = layui.table;
    const reloadTable = () => {
      table.reload('fileTable', {
        data: fileList
      })
    }
    table.render({
      elem: '#fileTable'
      , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
      , cols: [[
        // {type:'checkbox'}
        , { field: 'name', title: '文件名', width: 250 }
        , { field: 'type', title: '文件类型', width: 120 }
        , { field: 'path', title: '文件路径' }
        , {
          field: 'size', title: '文件大小', sort: true, width: 120, templet: function (d) {
           return formatFileSize(d.size)
          }
        }
        , { field: 'md5', title: '文件MD5', width: 300 }
        , {
          field: 'status', title: '文件状态', width: 120, templet: function (d) {
            let temp = []
            if (d.status == 0) {
              temp.push('<span class="layui-badge layui-bg-green">已上传</span>')
            } else if (d.status == 1) {
              temp.push('<span class="layui-badge layui-bg-cyan">待上传</span>')
            } else if (d.status == 2) {
              temp.push('<div class="layui-progress layui-progress-big" lay-showPercent="yes" style="margin-top: 5px;">')
              temp.push('<div class="layui-progress-bar" lay-percent="' + parseInt(d.process) + '%"></div>')
              temp.push('</div>')
            }
            return temp.join('')
          }
        }
        , { field: 'tools', title: '操作', width: 200, toolbar: '#barTools' }
      ]]
      , even: true
      , limit: 1000
      , data: fileList
      , done: function (res, curr, count) {
        element.init();
      }
    });

    //监听行工具事件
    table.on('tool(fileTable)', function (obj) {
      var data = obj.data;
      //console.log(obj)
      if (obj.event === 'del') {
        layer.confirm('真的删除行么?', function (index) {
          // 根据fileList数组里面对象的Id字段匹配，从数组中删除
          fileList = fileList.filter(function (item) {
            return item.id !== data.id
          })
          reloadTable()
          layer.close(index);
        });
      } else if (obj.event === 'pass') {

      }
    });
  });
}